package com.bw.utils;

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.Date;

public class DateTimeUtil {

    private final static DateTimeFormatter formater = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    public static String toYMDhms(Date date) {
        LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
        return formater.format(localDateTime);
    }

    public static Long toTs(String YmDHms) {
        LocalDateTime localDateTime = LocalDateTime.parse(YmDHms, formater);
        return localDateTime.toInstant(ZoneOffset.of("+8")).toEpochMilli();
    }

    public static int getAge(String birthday) {
        if (birthday.contains(" ")) {
            birthday = birthday.split(" ")[0];
        }
        LocalDate currentDate = LocalDate.now();
        // 将字符串转换为LocalDate类型
        LocalDate birthDate = LocalDate.parse(birthday);
        // 计算年龄
        Period period = Period.between(birthDate, currentDate);
        int age = period.getYears();
        return age;
    }
}

